package com.yuexunit.finance.system.service;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.yuexunit.finance.system.entity.UserCardInfoEntity;
import com.yuexunit.finance.system.entity.lexicon.CardStatusEnum;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;


/**
 * @author wenwenlong
 */
@Implements(UserCardInfoService.class)
public class UserCardInfoServiceImpl implements UserCardInfoService {

	@Override
	@Transactional
	public Long createUserCardInfo(UserCardInfoEntity entity) {
		entity.setEnabled(Boolean.TRUE);
		PersistUtil.insert(entity);
		return entity.getUserCardId();
	}

	@Override
	@Transactional
	public void updateUserCardInfo(UserCardInfoEntity entity) {
		PersistUtil.update(entity);
	}

	@Override
	public UserCardInfoEntity inquireUserCardInfoDetail(Long userCardId) {
		return PersistUtil.get(UserCardInfoEntity.class, userCardId);
	}
	
	@Override
	public UserCardInfoEntity inquireUserCardInfoDetailFromEnterpriseId(Long enterpriseId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserCardInfoEntity.class);
		criteria.add(Restrictions.eq("enterpriseId", enterpriseId));
		List<UserCardInfoEntity> list = PersistUtil.get(criteria);
		if (!list.isEmpty()) {
			int last = list.size() - 1;
			return list.get(last);
		} else {
			return null;
		}
	}

	@Override
	public PageList<UserCardInfoEntity> inquireUserCardInfoPageList(PageCriteria page) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserCardInfoEntity.class);
		return PersistUtil.get(criteria, page);
	}

	@Override
	public List<UserCardInfoEntity> inquireUserCardInfoList(String cardNumber) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserCardInfoEntity.class);
		criteria.add(Restrictions.eq("cardNumber", cardNumber));
		return PersistUtil.get(criteria);
	}

	@Override
	public List<UserCardInfoEntity> inquireUserCardInfoList(Long enterpriseId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserCardInfoEntity.class);
		criteria.add(Restrictions.eq("enterpriseId", enterpriseId));
		return PersistUtil.get(criteria);
	}

	@Override
	public List<Long> countUserCards() {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserCardInfoEntity.class);
		criteria.add(Restrictions.eq("cardStatus", CardStatusEnum.UNAUDIT));
		criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("userCardId")));
		return PersistUtil.get(criteria);
	}
}
